<template>
  <div class="main-layout">
    <Sidebar />
    
    <div class="main-content">
      <div class="header">
        <h2>数字人生成</h2>
        <div class="header-actions">
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      
      <div class="content">
        <div class="function-container">
          <el-row :gutter="20">
            <el-col :xs="24" :lg="14">
              <el-card class="upload-section">
                <template #header>
                  <div class="section-header">
                    <el-icon><Upload /></el-icon>
                    <span>输入配置</span>
                  </div>
                </template>
                
                <el-form
                  ref="digitalHumanFormRef"
                  :model="digitalHumanForm"
                  :rules="digitalHumanRules"
                  label-width="120px"
                  size="large"
                >
                  <el-form-item label="参考音频" prop="referenceAudio">
                    <el-upload
                      ref="audioUploadRef"
                      class="upload-demo"
                      drag
                      :auto-upload="false"
                      :on-change="handleAudioChange"
                      :before-remove="handleAudioRemove"
                      accept="audio/*"
                      :limit="1"
                    >
                      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                      <div class="el-upload__text">
                        将参考音频文件拖拽到此处，或<em>点击上传</em>
                      </div>
                      <template #tip>
                        <div class="el-upload__tip">
                          支持 wav、mp3、m4a 格式，文件大小不超过 10MB
                        </div>
                      </template>
                    </el-upload>
                    
                    <div v-if="digitalHumanForm.referenceAudio" class="uploaded-file">
                      <el-icon><Document /></el-icon>
                      <span>{{ digitalHumanForm.referenceAudio.name }}</span>
                      <el-button
                        type="danger"
                        size="small"
                        text
                        @click="handleAudioRemove"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </el-form-item>
                  
                  <el-form-item label="文本内容" prop="text">
                    <el-input
                      v-model="digitalHumanForm.text"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入要合成的文本内容..."
                      maxlength="1000"
                      show-word-limit
                    />
                  </el-form-item>
                  
                  <el-form-item label="人物形象视频" prop="characterVideo">
                    <el-upload
                      ref="videoUploadRef"
                      class="upload-demo"
                      drag
                      :auto-upload="false"
                      :on-change="handleVideoChange"
                      :before-remove="handleVideoRemove"
                      accept="video/*"
                      :limit="1"
                    >
                      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                      <div class="el-upload__text">
                        将人物形象视频拖拽到此处，或<em>点击上传</em>
                      </div>
                      <template #tip>
                        <div class="el-upload__tip">
                          支持 mp4、avi、mov 格式，建议人物正面清晰可见
                        </div>
                      </template>
                    </el-upload>
                    
                    <div v-if="digitalHumanForm.characterVideo" class="uploaded-file">
                      <el-icon><VideoCamera /></el-icon>
                      <span>{{ digitalHumanForm.characterVideo.name }}</span>
                      <el-button
                        type="danger"
                        size="small"
                        text
                        @click="handleVideoRemove"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </el-form-item>
                  
                  <el-form-item label="生成参数">
                    <el-row :gutter="10">
                      <el-col :span="8">
                        <el-form-item label="推理模式" prop="inferenceMode">
                          <el-select v-model="digitalHumanForm.inferenceMode" style="width: 100%">
                            <el-option label="普通模式" value="normal" />
                            <el-option label="批量模式" value="batch" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="解析模式" prop="parseMode">
                          <el-select v-model="digitalHumanForm.parseMode" style="width: 100%">
                            <el-option label="处理面颊" value="processed" />
                            <el-option label="原始模式" value="raw" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="视频质量" prop="quality">
                          <el-select v-model="digitalHumanForm.quality" style="width: 100%">
                            <el-option label="高质量" value="high" />
                            <el-option label="标准质量" value="medium" />
                            <el-option label="快速生成" value="low" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  
                  <!-- <el-form-item label="语音参数">
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="语速" prop="speed">
                          <el-slider
                            v-model="digitalHumanForm.speed"
                            :min="0.5"
                            :max="2.0"
                            :step="0.1"
                            show-input
                            :format-tooltip="formatSpeed"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="音调" prop="pitch">
                          <el-slider
                            v-model="digitalHumanForm.pitch"
                            :min="0.5"
                            :max="2.0"
                            :step="0.1"
                            show-input
                            :format-tooltip="formatPitch"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form-item> -->
                  
                  <el-form-item>
                    <el-button
                      type="primary"
                      size="large"
                      :loading="isGenerating"
                      @click="handleGenerate"
                      style="width: 100%"
                    >
                      <el-icon><User /></el-icon>
                      {{ isGenerating ? '生成中...' : '开始生成数字人视频' }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            
            <el-col :xs="24" :lg="10">
              <el-card class="result-section">
                <template #header>
                  <div class="section-header">
                    <el-icon><VideoPlay /></el-icon>
                    <span>生成结果</span>
                  </div>
                </template>
                
                <div v-if="!generatedVideo && !isGenerating" class="empty-result">
                  <el-icon class="empty-icon"><User /></el-icon>
                  <p>请先配置参数并生成数字人视频</p>
                </div>
                
                <div v-if="isGenerating" class="generating">
                  <el-progress
                    :percentage="progress"
                    :status="progress === 100 ? 'success' : undefined"
                  />
                  <p class="progress-text">{{ progressText }}</p>
                </div>
                
                <div v-if="generatedVideo" class="video-result">
                  <div class="video-info">
                    <h4>生成成功！</h4>
                    <p>视频时长：{{ videoDuration }}</p>
                    <p>文件大小：{{ videoSize }}</p>
                    <p>分辨率：{{ videoResolution }}</p>
                    <p>生成时间：{{ generationTime }}</p>
                  </div>
                  
                  <div class="media-player">
                    <video
                      ref="videoPlayerRef"
                      :src="generatedVideo"
                      controls
                      preload="metadata"
                      style="width: 100%; border-radius: 8px;"
                    >
                      您的浏览器不支持视频播放
                    </video>
                  </div>
                  
                  <div class="video-actions">
                    <el-button
                      type="primary"
                      @click="playVideo"
                      :disabled="isPlaying"
                    >
                      <el-icon><VideoPlay /></el-icon>
                      {{ isPlaying ? '播放中...' : '播放' }}
                    </el-button>
                    <el-button @click="downloadGeneratedVideo">
                      <el-icon><Download /></el-icon>
                      下载
                    </el-button>
                    <el-button @click="clearResult">
                      <el-icon><Delete /></el-icon>
                      清除
                    </el-button>
                  </div>
                </div>
                
                <div v-if="errorMessage" class="error-message">
                  <el-alert
                    :title="errorMessage"
                    type="error"
                    :closable="false"
                    show-icon
                  />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import Sidebar from '@/components/Sidebar.vue'
// 注销用于测试，导入API
// import { generateDigitalHuman, connectProgressWebSocket, downloadVideo } from '@/api/digitalHuman'

const digitalHumanFormRef = ref()
const audioUploadRef = ref()
const videoUploadRef = ref()
const videoPlayerRef = ref()

const isGenerating = ref(false)
const isPlaying = ref(false)
const progress = ref(0)
const progressText = ref('')
const generatedVideo = ref('')
const videoDuration = ref('')
const videoSize = ref('')
const videoResolution = ref('')
const generationTime = ref('')
const errorMessage = ref('')

const digitalHumanForm = reactive({
  referenceAudio: null,
  text: '',
  characterVideo: null,
  inferenceMode: 'normal',
  parseMode: 'processed',
  quality: 'medium',
  speed: 1.0,
  pitch: 1.0
})

const digitalHumanRules = {
  referenceAudio: [
    { required: true, message: '请上传参考音频文件', trigger: 'change' }
  ],
  text: [
    { required: true, message: '请输入要合成的文本', trigger: 'blur' },
    { min: 1, max: 1000, message: '文本长度在 1 到 1000 个字符', trigger: 'blur' }
  ],
  characterVideo: [
    { required: true, message: '请上传人物形象视频', trigger: 'change' }
  ]
}

const formatSpeed = (value) => {
  return `${value}x`
}

const formatPitch = (value) => {
  return `${value}x`
}

const handleAudioChange = (file) => {
  digitalHumanForm.referenceAudio = file.raw
  digitalHumanFormRef.value?.validateField('referenceAudio')
}

const handleAudioRemove = () => {
  digitalHumanForm.referenceAudio = null
  audioUploadRef.value?.clearFiles()
  digitalHumanFormRef.value?.validateField('referenceAudio')
}

const handleVideoChange = (file) => {
  digitalHumanForm.characterVideo = file.raw
  digitalHumanFormRef.value?.validateField('characterVideo')
}

const handleVideoRemove = () => {
  digitalHumanForm.characterVideo = null
  videoUploadRef.value?.clearFiles()
  digitalHumanFormRef.value?.validateField('characterVideo')
}

const handleGenerate = async () => {
  if (!digitalHumanFormRef.value) return
  
  try {
    const valid = await digitalHumanFormRef.value.validate()
    if (!valid) return
    
    isGenerating.value = true
    errorMessage.value = ''
    progress.value = 0
    
    // 调用后端API生成数字人视频
    await generateDigitalHumanVideo()
    
  } catch (error) {
    errorMessage.value = '生成失败：' + error.message
    ElMessage.error('生成失败')
    isGenerating.value = false
  }
}

const generateDigitalHumanVideo = async () => {
  try {
    // 模拟生成过程
    const steps = [
      { progress: 10, text: '正在上传文件...' },
      { progress: 25, text: '正在分析参考音频...' },
      { progress: 40, text: '正在提取视频中的人物信息...' },
      { progress: 55, text: '正在生成TTS语音...' },
      { progress: 70, text: '正在对齐音频和视频...' },
      { progress: 85, text: '正在生成面部动作...' },
      { progress: 95, text: '正在渲染视频帧...' },
      { progress: 100, text: '生成完成！' }
    ]
    
    for (const step of steps) {
      progress.value = step.progress
      progressText.value = step.text
      await new Promise(resolve => setTimeout(resolve, 2000))
    }
    
    // 模拟生成成功
    generatedVideo.value = 'data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMWF2YzEAAAABAAABAAAAAAAwYWRtaW4AAAAgAAAABAAAACRkdW5lAAAAAA=='
    videoDuration.value = '0:15'
    videoSize.value = '8.5 MB'
    videoResolution.value = '1920x1080'
    generationTime.value = new Date().toLocaleString()
    
    isGenerating.value = false
    ElMessage.success('数字人视频生成成功！')
    
  } catch (error) {
    errorMessage.value = '生成失败：' + error.message
    isGenerating.value = false
    ElMessage.error('生成失败')
  }
}

const playVideo = () => {
  if (videoPlayerRef.value) {
    isPlaying.value = true
    videoPlayerRef.value.play()
  }
}

const downloadGeneratedVideo = async () => {
  if (generatedVideo.value) {
    try {
      // 直接下载生成的视频URL
      const link = document.createElement('a')
      link.href = generatedVideo.value
      link.download = `digital_human_${Date.now()}.mp4`
      link.click()
      ElMessage.success('下载已开始')
    } catch (error) {
      ElMessage.error('下载失败：' + error.message)
    }
  }
}

const clearResult = () => {
  generatedVideo.value = ''
  videoDuration.value = ''
  videoSize.value = ''
  videoResolution.value = ''
  generationTime.value = ''
  errorMessage.value = ''
  progress.value = 0
  progressText.value = ''
}

const refreshData = () => {
  clearResult()
  ElMessage.success('数据已刷新')
}

// 监听视频播放结束
onMounted(() => {
  if (videoPlayerRef.value) {
    videoPlayerRef.value.addEventListener('ended', () => {
      isPlaying.value = false
    })
  }
})

onUnmounted(() => {
  if (videoPlayerRef.value) {
    videoPlayerRef.value.removeEventListener('ended', () => {
      isPlaying.value = false
    })
  }
})
</script>

<style scoped>
.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.uploaded-file {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: var(--border-extra-light);
  border-radius: 6px;
  margin-top: 8px;
}

.empty-result {
  text-align: center;
  padding: 40px 20px;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 48px;
  color: var(--border-color);
  margin-bottom: 16px;
}

.generating {
  padding: 20px;
  text-align: center;
}

.progress-text {
  margin-top: 12px;
  color: var(--text-regular);
  font-size: 14px;
}

.video-result {
  padding: 20px 0;
}

.video-info {
  margin-bottom: 20px;
  padding: 16px;
  background: var(--border-extra-light);
  border-radius: 8px;
}

.video-info h4 {
  margin: 0 0 8px 0;
  color: var(--success-color);
  font-size: 16px;
}

.video-info p {
  margin: 4px 0;
  color: var(--text-regular);
  font-size: 14px;
}

.video-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.error-message {
  margin-top: 20px;
}

:deep(.el-upload-dragger) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-slider__runway) {
  margin: 12px 0;
}

:deep(.el-card__header) {
  border-bottom: 1px solid var(--border-extra-light);
}

:deep(.el-card__body) {
  padding: 24px;
}
</style>
